package com.rinlink.gateway.jt808.controller;

import com.alibaba.fastjson.JSONObject;
import com.rinlink.gateway.jt808.model.TerminalRequestMessage;
import com.rinlink.gateway.jt808.model.Base64Jt808ResponseInDTO;
import com.rinlink.gateway.jt808.model.NoticeMessageType;
import io.github.yhydev.lightbit.common.ByteBufUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;



@RestController
@RequestMapping("/webHook")
@Slf4j
public class TerminalsControllerTest {

    @Autowired
    WebClient webClientTest;

    @PostMapping
    public void webHook(@RequestBody JSONObject json) {
        log.info("WebHook: {}",json.toJSONString());
        String type = json.getString("type");

        if (type.equals(NoticeMessageType.TERMINAL_REQUEST_MESSAGE.name())) {
            deviceRequestMessageProcessor(json);
        }else if (type.equals(NoticeMessageType.TERMINAL_DISCONNECT.name())){
            deviceDisconnect(json);
        }
    }

    private void deviceDisconnect(JSONObject json){
        log.info("Terminal [{}] Disconnect ", json.getJSONObject("payload").getString("terminalId"));
    }

    private void deviceRequestMessageProcessor(JSONObject inDTO) {

        TerminalRequestMessage msg = inDTO.getJSONObject("payload").toJavaObject(TerminalRequestMessage.class); //toJavaObject(NoticeMessageOutDTO.class);
        if (msg.getHeader().getMsgId() == 0x0100){
            terminalRegisterResponse(msg);
        }
    }

    private void terminalRegisterResponse(TerminalRequestMessage message){

        byte[] data = ByteBufUtils.INSTANCE.allocatorToBytes(e->{
            e.writeShort(message.getHeader().getFlowId())
                    .writeByte(0)
                    .writeBytes("123456".getBytes());
        });

        Base64Jt808ResponseInDTO inDTO = new Base64Jt808ResponseInDTO()
            .setBody(Base64Utils.encodeToString(data))
            .setMsgId((short)0x8100);


        webClientTest
                .post()
                .uri("/terminals/{terminalId}/response/base64",message.getHeader().getTerminalId())
                .syncBody(inDTO)
                .exchange().subscribe(e->{
                    log.info("post success");
                },e->{
                    log.warn("Register response error",e);
                });


    }


}
